package com.shiyipicture.shiyipicturebackend.api.imageSearch.sub;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.JsonObject;
import com.shiyipicture.shiyipicturebackend.api.imageSearch.model.ImageSearchResult;
import com.shiyipicture.shiyipicturebackend.exception.BusinessException;
import com.shiyipicture.shiyipicturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class GetImageListApi {

  /**
   * 获取图片列表
   *
   * @param url
   * @return
   */
  public static List<ImageSearchResult> getImageList(String url){
    try {
      HttpResponse response = HttpRequest.get(url)
        .timeout(5000)
        .execute();
      int status = response.getStatus();
      String responseBody = response.body();

      if (status == 200) {
        return getImageSearchResults(responseBody);
      }else{
        throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败");
      }
    } catch (HttpException e) {
      log.error("获取图片列表失败", e);
      throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取图片列表失败");
    }
  }

  /**
   * 处理接口响应内容
   *
   * @param responseBody 接口返回的JSON字符串
   */
  private static List<ImageSearchResult> getImageSearchResults(String responseBody) {
    JSONObject jsonObject = new JSONObject(responseBody);
    if (!jsonObject.containsKey("data")) {
      throw new BusinessException(ErrorCode.OPERATION_ERROR, "未获取到图片列表");
    }
    JSONObject data = jsonObject.getJSONObject("data");

    if (!data.containsKey("list")) {
      throw new BusinessException(ErrorCode.OPERATION_ERROR, "未获取到图片列表");
    }
    JSONArray list = data.getJSONArray("list");
    return JSONUtil.toList(list, ImageSearchResult.class);
  }
}
